<?php

namespace App\Models;

use App\Http\Controllers\PdfController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛作品电子书表
 * Class ArticleModel
 * @package app\common\model
 */
class CompetiteActivityEbook extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'competite_activity_ebook';


    /**
     * @param database_id int 数据库id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param is_play int 是否发布 1 发布  2 未发布
     * @param keywords string 搜索关键词(作品数据库名称)
     * @param start_time datetime 投稿时间(开始)
     * @param end_time datetime 投稿时间(截止)
     */
    public function lists($database_id, $keywords, $is_play, $start_time, $end_time, $limit = null)
    {
        $res = $this->from($this->getTable() . ' as e')->select(
            'e.id',
            'e.name',
            'e.img',
            'e.author',
            'e.intro',
            'e.is_play',
            'e.create_time',
            'e.browse_num'
        )->join('competite_activity_works_ebook as we', 'we.ebook_id', '=', 'e.id')
            ->where(function ($query) use ($keywords) {
                $query->where('e.name', 'like', "%$keywords%");
            })->where(function ($query) use ($is_play, $start_time, $end_time) {
                if ($is_play) {
                    $query->where('e.is_play', $is_play);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('e.create_time', [$start_time, $end_time]);
                }
            })
            ->where('we.database_id', $database_id)
            ->where('e.is_del', 1)
            ->orderByDesc('e.sort')
            ->paginate($limit)
            ->toArray();

        return $res;
    }

    /**
     * 管理员详情
     * @param id 管理员id
     */
    public function detail($id, $field = null)
    {
        if (empty($field)) {
            $field = ['id', 'name', 'img', 'intro', 'is_play', 'author', 'create_time', 'browse_num'];
        }
        $res = $this->select($field)->where('is_del', 1)->where('id', $id)->first();

        return $res;
    }
}
